
M = require("ming_node")
M.log_display_time=false;
M.Db_table_prefix="mi_";
M.SPLIT="______";
newDatabase = {
    "host": "127.0.0.1",
    "user": "root",
    "password": "123456",
    "port": "3306",
    "database": "miapinew"
}
oldDatabase = {
    "host": "127.0.0.1",
    "user": "root",
    "password": "123456",
    "port": "3306",
    "database": "miapiold"
}


newDb = M.getMySql(newDatabase);
newDb.databaseConfig=newDatabase
M.mysql=null;
oldDb = M.getMySql(oldDatabase);
oldDb.databaseConfig=oldDatabase;



const SQL_TYPE={
    DROP_TABLE:0,
    CREATE_TABLE:1,
    ADD_FIELD:2,
    DELETE_FIELD:3,
    ADD_INDEX:4,
    DELETE_INDEX:5
}


M.getSql=async function(dataBase,type,content){
    if(SQL_TYPE.DROP_TABLE==type){
       let sql=`drop table ${dataBase.databaseConfig.database}.${content};`
       return sql;
    }
    if(SQL_TYPE.CREATE_TABLE==type){
        let sql=`show create table ${newDb.databaseConfig.database}.${content};`
        oldList=await newDb.doSql(sql)
        return oldList[0]["Create Table"];
     }
     if(SQL_TYPE.ADD_FIELD==type){
        let cList= content.split(M.SPLIT)
        let sql=`alter table ${dataBase.databaseConfig.database}.${cList[0]} add ${cList[1]} ${cList[2]} COMMENT '${cList[3]}';`
        return sql;
     }
     if(SQL_TYPE.DELETE_FIELD==type){
        let cList= content.split(M.SPLIT)
        let sql=`alter table ${dataBase.databaseConfig.database}.${cList[0]} DROP  ${cList[1]};`
        return sql;
     }
     if(SQL_TYPE.ADD_INDEX==type){
        let cList= content.split(M.SPLIT)
        let sql=`alter table ${dataBase.databaseConfig.database}.${cList[0]} add unique ${cList[1]}(${cList[2]});`
        return sql;
     }
     if(SQL_TYPE.DELETE_INDEX==type){
        let cList= content.split(M.SPLIT)
        let sql=`alter table ${dataBase.databaseConfig.database}.${cList[0]} drop index ${cList[1]};`
        return sql;
     }
    
}



async function main(){


    M.readLine("M.log",async (line)=>{
        let sql="";
        lineArr= line.split(" ")
        let sqlType="";
        if(lineArr[1]=="新增表"){
            sqlType=SQL_TYPE.CREATE_TABLE
        }
        if(lineArr[1]=="删除表"){
            sqlType=SQL_TYPE.DROP_TABLE
        }
        if(lineArr[1]=="删除字段"){
            sqlType=SQL_TYPE.DELETE_FIELD
        }
        if(lineArr[1]=="新增字段"){
            sqlType=SQL_TYPE.ADD_FIELD
        }
        if(lineArr[1]=="删除索引"){
            sqlType=SQL_TYPE.DELETE_INDEX
        }
        if(lineArr[1]=="新增索引"){
            sqlType=SQL_TYPE.ADD_INDEX
        }
        sql= await M.getSql(oldDb,sqlType,lineArr[2])
        console.log(lineArr)
        M.appendFile("result.sql","-- " +line+"\n")
        M.appendFile("result.sql",sql+"\n")
    })


 }

main()

setTimeout(()=>process.exit(),1000)